<?php
class PostTagModel extends MY_Model{
    public $table = 't_post_tag';
    public function __construct(){
        parent::__construct();
    }


    /**
     * 通过postid取出所有的标签
     * name: get_post_topic
     * @param $id
     * @return array
     * @throws Exception
     * @Author:taiyang
     */
    public function get_post_tag($id){
        if(empty($id)){return array();}
        $sql="select t.* from ".$this->table." pt  
                left join t_tag t on t.id=pt.tag_id 
                where 1 and pt.post_id='".$id."' and pt.status=1";
        $res=$this->query_sql_list($sql);
        if(empty($res)){return array();}
        $ids=array();
        foreach ($res as $k=>$v){
            $ids[]=$v['id'];
        }
        return array("ids"=>$ids,'list'=>$res);
    }

    /**
     * 添加删除标签
     * name: del_add_post_tag
     * @param $post_id
     * @param $tag_id
     * @param int $type 1添加2删除
     * @return bool
     * @throws Exception
     * @Author:taiyang
     */
    public function del_add_post_tag($post_id,$tag_id,$type=1){
        if(empty($tag_id) || empty($post_id)){return false;}
        $res=$this->PostTagModel->query_one(array('post_id'=>$post_id,'tag_id'=>$tag_id));
        if($type == 1){
            if(empty($res)){
                $this->PostTagModel->insert_one(array('post_id'=>$post_id,'tag_id'=>$tag_id));
            }else{
                $this->PostTagModel->update_data(array('status'=>1),array('post_id'=>$post_id,'tag_id'=>$tag_id));
            }
            $num="+1";
        }else{
            $this->PostTagModel->update_data(array('status'=>-1),array('post_id'=>$post_id,'tag_id'=>$tag_id));
            $num="-1";
        }
        //修改数据
        $this->TagModel->db->set('post_num',"post_num".$num."",false);
        $this->TagModel->db->where('id', $tag_id);
        $this->TagModel->db->update('t_tag');
        return true;
    }

}